package controllers

import (
	"crypto/md5"
	"fmt"
	"github.com/astaxie/beego"
	"io"
	"math/rand"
	"os"
	"path"
	"softwareEngineering/models"
	"strconv"
	"time"
)

type UploadController struct {
	beego.Controller
}

func (c *UploadController) UpForm() {
	c.TplName = "upload.html"
}

func (c *UploadController) UpFile() {
	user := c.Ctx.Input.Session("user").(models.User)

	f, err := c.GetFiles("myfile") //获取上传的文件
	if err != nil {
		fmt.Println(err)
		return
	}
	for i, _ := range f {
		file, err := f[i].Open()
		ext := path.Ext(f[i].Filename)
		//验证后缀名是否符合要求
		var AllowExtMap map[string]bool = map[string]bool{
			".jpg":  true,
			".jpeg": true,
			".png":  true,
			".txt":  true,
			".md":   true,
			".mp4":  true,
		}
		if _, ok := AllowExtMap[ext]; !ok {
			c.Ctx.WriteString("后缀名不符合上传要求")
			return
		}

		if err != nil {
			c.Ctx.WriteString("读取图片出错")
			return
		}
		//创建目录
		uploadDir := "static/upload/" + time.Now().Format("2006/01/02/")
		err = os.MkdirAll(uploadDir, 777)
		if err != nil {
			c.Ctx.WriteString(fmt.Sprintf("%v", err))
			return
		}
		//构建文件名
		rand.Seed(time.Now().UnixNano())
		randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000)
		hashName := md5.Sum([]byte(time.Now().Format("2006_01_02_15_04_05_") + randNum))
		fileName := fmt.Sprintf("%x", hashName) + ext
		//构建文件名结束
		fpath := uploadDir + fileName

		dst, err := os.Create(fpath)
		if err != nil {
			c.Ctx.WriteString(fmt.Sprintf("%v", err))
			return
		}
		if _, err := io.Copy(dst, file); err != nil {
			fmt.Println("上传失败")
			c.Data["videos"] = QueryVideoByUserId(strconv.Itoa(user.Id))
			c.Data["articles"] = QueryAllArticle(user)
			c.Data["uploadSuccess"] = "uploadFailed"
			c.TplName = "tip.html"
		} else {
			switch ext {
			case ".md":
				FileUploadSql(user, fileName, fpath)
			case ".mp4":
				UploadVideo(user.Id, fileName, fpath, "", "")
			default:
				ImageUploadSql(user, fileName, fpath)
			}

		}
		c.Data["videos"] = QueryVideoByUserId(strconv.Itoa(user.Id))
		c.Data["articles"] = QueryAllArticle(user)
		c.Data["uploadSuccess"] = "uploadSuccess"
		c.TplName = "tip.html"
	}
}
